package guestbook;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GuestbookServlet
	extends HttpServlet
{
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException
	{
		String guestbookName="testNameForGuestbook";
		Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
		Entity greeting = new Entity("Greeting", guestbookKey);

		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		Query q = new Query("accessNumber");
		PreparedQuery pq = datastore.prepare(q);
		List<Entity> result=pq.asList(FetchOptions.Builder.withLimit(1));
		
		int accessNumber=0;
		
		if (result!=null && result.size()>0 )
		{
			Entity accessNumbeEntity=result.get(0);
			accessNumber=Integer.valueOf( accessNumbeEntity.getProperty("accessNumber").toString() );
			accessNumbeEntity.setProperty( "accessNumber", Integer.toString(++accessNumber) );
			datastore.put(accessNumbeEntity);
		}
		else
		{
			++accessNumber;
			Entity accessNumbeEntity=new Entity( "accessNumber", guestbookKey);
			accessNumbeEntity.setProperty( "accessNumber", Integer.toString(accessNumber) );
			datastore.put(accessNumbeEntity);
		}
		
		resp.setContentType("text/plain");
		resp.getWriter().println( "Hello, world of chess. This page has been accessed: "+Integer.toString(accessNumber) );
		
		resp.sendRedirect("/guestbook");

	}
}
